<template>

  <el-upload
    ref="upload"
    :accept="upload.exts"
    :action="upload.url"
    :auto-upload="autoUpload"
    :before-upload="handleBeforeUpload"
    :data="upload.data"
    :disabled="disabled"
    :file-list="upload.fileList"
    :headers="upload.headers"
    :limit="limit"
    :multiple="multiple"
    :on-error="handleFileError"
    :on-preview="handleFilePreview"
    :on-progress="handleFileUploadProgress"
    :on-remove="handleFileRemove"
    :on-success="handleFileSuccess"
  >
    <el-button slot="trigger" :class="hidden ? 'hidden' : ''" :disabled="disabled" :size="size"><i
      class="el-icon-upload2"
    ></i><span class="upload-btn-text">上 传</span></el-button>

  </el-upload>

</template>

<script>
import { getToken } from '@/utils/auth'
import { delAttachment, getAttachment, listByBusinessKeyAndUploaderId } from '../../api/attachment'
import emitter from 'element-ui/src/mixins/emitter'
import { getAfterRentFile } from '@/api/hsrzzl/afterRent/archives'
import { deleteAfterRentFileByAttachmentId } from '../../api/hsrzzl/afterRent/archives'

export default {
  name: 'ArchiveAttachment',
  mixins: [emitter],
  model: {
    prop: 'uploadValue',
    event: 'change'
  },
  props: {
    disabled: {
      required: false,
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'small'
    },
    accept: {
      required: false,
      type: String
    },
    moduleName: {
      required: false,
      type: String
    },
    businessId: {
      required: false,
      type: Number
    },
    uploaderId: {
      required: false,
      type: String
    },
    archiveId: {
      required: false,
      type: Number
    },
    attachmentId: {
      required: false,
      type: Number
    },
    onFileSuccess: {
      required: false,
      type: Function
    },
    uploadSizeLimit: {
      required: false,
      type: Number,
      default: 10
    },
    limit: {
      required: false,
      type: Number,
      default: 10
    },
    hidden: {
      type: Boolean,
      default: false
    },
    uploadValue: {
      type: Number,
      default: 0
    },
    autoUpload: {
      type: Boolean,
      default: true
    },
    multiple: {
      type: Boolean,
      default: false
    },
    show: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      //上传的附件ID拼接的字符串，新增时使用
      uploadAttachmentIds: '',
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/enterprise/attachment/upload',
        // 上传的文件列表
        fileList: [],
        // 接受的格式
        exts: '.jpg,.png,.gif,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf',
        // 上传附带的数据
        data: {
          moduleName: this.moduleName,
          uploaderId: this.uploaderId,
          businessKey: this.uploaderId + this.businessId
        },
        limit: this.uploadSizeLimit
      }
    }
  },

  created() {
    //重置接收文件格式
    if (this.accept) {
      this.upload.exts = this.accept
    }
    console.log(this.businessId)
    this.initFileList()
  },
  methods: {
    cancel() {
      // this.clearFiles()
      this.$refs.upload.clearFiles()
    },
    /**初始化文件队列*/
    initFileList() {
      if (this.businessId && this.upload.data.uploaderId) {
        listByBusinessKeyAndUploaderId(this.businessId, this.upload.data.uploaderId).then(response => {
          this.upload.fileList = response.map(element => {
            return {
              status: 'success',
              name: element.originalName,
              size: element.fileSize,
              percentage: 100,
              response: {
                attachmentId: element.id,
                fileName: element.fileName,
                url: process.env.VUE_APP_BASE_API + element.fileName
              }
            }
          })

          //如果首次进入，没有文件，不触发验证
          if (this.upload && this.upload.fileList && this.upload.fileList.length > 0) {
            this.dispatchParentValidate()
          }
        })
      } else if (this.archiveId) {
        console.log(this.archiveId)
        getAfterRentFile(this.archiveId).then(res => {
          if (res) {
            getAttachment(res.data.attachmentId).then(res2 => {
              let file = res2.data
              this.upload.fileList.push(
                {
                  status: 'success',
                  name: file.originalName,
                  size: file.fileSize,
                  percentage: 100,
                  response: {
                    attachmentId: file.id,
                    fileName: file.fileName,
                    url: process.env.VUE_APP_BASE_API + file.fileName
                  }
                }
              )
            })
          }
        })
      } else if (this.attachmentId) {
        getAttachment(this.attachmentId).then(res => {
          console.log(res)
          let file = res.data
          this.upload.fileList.push(
            {
              status: 'success',
              name: file.originalName,
              size: file.fileSize,
              percentage: 100,
              response: {
                attachmentId: file.id,
                fileName: file.fileName,
                url: process.env.VUE_APP_BASE_API + file.fileName
              }
            }
          )
        })
      }
    },
    // 判断文件是否上传 -- 未完成
    // judgeFileList(){
    //   if (this.businessId && this.upload.data.uploaderId) {
    //     listByBusinessKeyAndUploaderId(this.businessId, this.upload.data.uploaderId).then(response => {
    //       console.log("文件是都上传:" + JSON.stringify(response))
    //     })
    //   }
    // },
    // 文件上传前处理
    handleBeforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (this.accept && this.accept.indexOf(fileSuffix) === -1) {
        this.$message({
          type: 'error',
          message: '上传文件只能是' + this.accept + '格式'
        })
        return false
      }

      // 上传大小检查，以M为单位
      const uploadSizeLimit = this.uploadSizeLimit * 1024 * 1024
      if (!file || file && file.size > uploadSizeLimit) {
        this.msgError('上传文件大小不能大于' + this.uploadSizeLimit + 'M')
        return false
      }

    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code === 200) {
        console.log(fileList)
        this.upload.isUploading = false

        if (this.uploadAttachmentIds) {
          this.uploadAttachmentIds += ',' + response.attachmentId
        } else {
          this.uploadAttachmentIds = response.attachmentId
        }
        //处理文件队列里面url的基础路径
        this.upload.fileList = fileList.map(item => {
          if (item.response) {
            item.response.url = process.env.VUE_APP_BASE_API + item.response.fileName
          }
          return item
        })
        this.dispatchParentValidate()
        this.$emit('onFileSuccess', this.uploadAttachmentIds, fileList)
        this.msgSuccess(response.msg)

        if (!this.show) {
          this.clearFiles()
        }
      } else {
        this.msgError(response.msg)
      }

    },
    //文件上传失败
    handleFileError(err, file, fileList) {
      this.msgError('上传错误')
    },
    // 文件删除处理
    handleFileRemove(file, fileList) {
      if (file && file.response) {
        let attachmentId = parseInt(file.response.attachmentId)
        delAttachment(attachmentId).then(response => {
          this.upload.fileList = fileList

          this.dispatchParentValidate()

          deleteAfterRentFileByAttachmentId(attachmentId).then(response => {
            if (response.code === 200) {
              this.uploadAttachmentIds = String(this.uploadAttachmentIds).replace(',' + attachmentId, '').replace(attachmentId, '')
              this.$emit('onFileRemove', attachmentId)
              this.msgSuccess('档案删除成功')
            }
          })

        })
      }
    },
    //文件预览
    handleFilePreview(file) {
      if (file && file.response) {
        window.open(file.response.url)
      }
    },
    //清空队列
    clearFiles() {
      this.upload.fileList = []
      this.upload.data = {
        moduleName: this.moduleName,
        uploaderId: this.uploaderId,
        businessKey: this.uploaderId + this.businessId
      }
      this.uploadAttachmentIds = ''
      this.$refs.upload.clearFiles()
    },
    //设置businessId
    setBusinessId(businessId) {
      this.upload.data.businessKey = this.uploaderId + businessId
    },
    //触发父组件验证
    dispatchParentValidate() {
      const fileListNotEmpty = this.upload && this.upload.fileList && this.upload.fileList.length > 0 ? 1 : undefined
      this.$emit('change', fileListNotEmpty)
      this.dispatch('ElFormItem', 'el.form.blur', [fileListNotEmpty])
    }
  }
}
</script>

<style scoped>
.hidden {
  display: none;
}
</style>
